using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class LCScrollView : MonoBehaviour
{
    [SerializeField]
    private Transform content;
    [SerializeField]
    private GameObject item;
    public ScrollRect scrollView;
    private List<ScrollViewItem> items = new List<ScrollViewItem>();
    private bool isInit = false;
    public Action<int> clickEvent;

    public void Init<T>(Action<int> clickEvent = null) where T : ScrollViewItem
    {
        isInit = true;
        this.clickEvent = clickEvent;
        this.gameObject.SetActive(false);
    }
    public void Refresh(IList datas)
    {
        if (!isInit)
        {
            Debug.LogError("LCScrollView 未初始化");
            return;
        }
        if (datas == null)
        {
            this.gameObject.SetActive(false);
            return;
        }
        this.gameObject.SetActive(true);
        item.gameObject.SetActive(false);
        if (datas.Count > items.Count)
        {
            int creatCount = datas.Count - items.Count;
            for (int i = 0; i < creatCount; i++)
            {
                var obj = Instantiate(item);
                obj.transform.SetParent(content, false);
                var scrollViewItem = obj.GetComponent<ScrollViewItem>();
                scrollViewItem.Init(this);
                items.Add(scrollViewItem);
            }
        }
        for (int i = 0; i < items.Count; i++)
        {
            if (i < datas.Count)
            {
                items[i].ShowSelf();
                items[i].Refresh(i, datas[i]);
            }
            else
            {
                items[i].HideSelf();
            }
        }
    }
}
